<?php

namespace support;

use Exception;
use SplFileInfo;

class File extends SplFileInfo
{

    public function __construct(string $path)
    {
        parent::__construct($path);
    }

    public function move($path)
    {
        set_error_handler(function ($type, $msg) use (&$error) {
            $error = $msg;
        });
        $dir = pathinfo($path, PATHINFO_DIRNAME);
        if (!is_dir($dir) && !mkdir($dir, 0775, true)) {
            restore_error_handler();
            throw new Exception(sprintf('Unable to create the "%s" directory (%s)', $dir, strip_tags($error)));
        }
        $pathName = $this->getPathname();
        $renamed = rename($pathName, $path);
        restore_error_handler();
        if (!$renamed) {
            throw new Exception(sprintf('Could not move the file "%s" to "%s" (%s)', $pathName, $path, strip_tags($error)));
        }
        @chmod($path, 0666 & ~umask());
        return new self($path);
    }

    public function getRealMime()
    {
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mimeType = finfo_file($finfo, $this->getPathname());
        finfo_close($finfo);
        return $mimeType;
    }
}
